package com.farseer810.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.farseer810.model.Class;
import com.farseer810.model.Student;;

public class CourseService {
	public static final int CHINESE = 0;
	public static final int MATH = 1;
	public static final int ENGLIST = 2;
	public static final int TOTAL_SCORE = 3;

	private CourseService() {
	}

	@SuppressWarnings("unchecked")
	public static HashMap<Integer, HashMap<String, Object>> getCourseGradeList(int courseType) throws Exception {
		List<Student> studentList = StudentService.getStudentGradeList(StudentService.SORT_TOTAL_SCORE);
		
		HashMap<Integer, HashMap<String, Object>> result = new HashMap<>();
		for (Student student : studentList) {
			Class belongClass = student.getBelongClass();
			if(!result.containsKey(belongClass.getId())) {
				HashMap<String, Object> m = new HashMap<>();
				m.put("name", belongClass.getName());
				
				List<Student> list = new ArrayList<Student>();
				list.add(student);
				m.put("best", list);
				
				list = new ArrayList<Student>();
				list.add(student);
				m.put("worst", list);
				result.put(belongClass.getId(), m);
			} else {
				HashMap<String, Object> m = result.get(belongClass.getId());
				Student bestStudent = ((List<Student>)m.get("best")).get(0);
				Student worstStudent = ((List<Student>)m.get("worst")).get(0);
				
				int bestScore = bestStudent.getTotalScore(), worstScore = worstStudent.getTotalScore(), 
						currentScore = student.getTotalScore();
				
				if(courseType == CHINESE) {
					currentScore = student.getChineseScore();
					bestScore = bestStudent.getChineseScore();
					worstScore = worstStudent.getChineseScore();
				} else if(courseType == MATH) {
					currentScore = student.getMathScore();
					bestScore = bestStudent.getMathScore();
					worstScore = worstStudent.getMathScore();
				} else if(courseType == ENGLIST) {
					currentScore = student.getEnglishScore();
					bestScore = bestStudent.getEnglishScore();
					worstScore = worstStudent.getEnglishScore();
				}
				
				if(bestScore == currentScore) {
					((List<Student>)m.get("best")).add(student);
				} else if(bestScore < currentScore) {
					List<Student> list = ((List<Student>)m.get("best"));
					list.clear();
					list.add(student);
				}
				
				if(worstScore == currentScore) {
					((List<Student>)m.get("worst")).add(student);
				} else if(worstScore > currentScore) {
					List<Student> list = ((List<Student>)m.get("worst"));
					list.clear();
					list.add(student);
				}
			}
		}
		
		return result;
	}
}
